package com.axxc.jpa.entity;

import java.util.Date;

import javax.persistence.PostPersist;
import javax.persistence.PostRemove;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @ClassName: BaseEntityDateListener
 * @Description: 基类监听器,执行初始化的一些操作
 * @author xxc
 * @date 2018年8月10日 下午2:48:57
 * @see https://bbs.csdn.net/topics/391839871
 * @see com.axxc.jpa.task.rabbitmsg.provider.RabbitMqTestPersonEntityMsgProviderTask
 * @see {@link https://www.concretepage.com/java/jpa/jpa-entitylisteners-example-with-callbacks-prepersist-postpersist-postload-preupdate-postupdate-preremove-postremove}
 */
@Component
public class BaseEntityDateListener {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@PrePersist
	public void initEntity(BaseEntity e) {
		this.logger.info("PrePersist-->持久化前	e:{}", JSONObject.toJSONString(e));
		e.setCreateDate(new Date());// 设置时间
		e.setUpdateDate(new Date());

	}

	@PostPersist
	public void testPostPersist(BaseEntity e) {
		// TODO 持久化后
		this.logger.info("PostPersist-->持久化后回调的方法e:{}", JSONObject.toJSONString(e));
	}

	// @PreRemove
	// public void testPreRemove(BaseEntity e) {
	// //TODO 删除前
	// this.logger.info("PreRemove-->删除前,当前时间:{{}},id:{{}}", currentTime(new
	// Date()), e.getId());
	// }

	@PostRemove
	public void testPostRemove(BaseEntity e) {
		// TODO 删除后
		this.logger.info("PostRemove-->删除后,当前时间:{{}},e:{}", currentTime(new Date()), JSONObject.toJSONString(e));
	}

	@PreUpdate
	public void updateEntity(BaseEntity e) {
		// TODO PreUpdate-->修改数据库前,若修改名称,则拼音也许修改
		this.logger.info("PreUpdate-->修改数据库前e:{},修改时间:{{}}", JSONObject.toJSONString(e),
				currentTime(e.getUpdateDate()));
		e.setUpdateDate(new Date());
	}

	@PostUpdate
	public void testPostUpdate(BaseEntity e) {
		// TODO PostUpdate-->修改数据库后
		this.logger.info("PostUpdate-->修改数据库后,e:{},修改时间:{{}}", JSONObject.toJSONString(e),
				currentTime(e.getUpdateDate()));
	}

	// @PostLoad
	// public void testPostLoad(BaseEntity e) {
	// // 查询,修改,删除会执行,新增前不会执行
	// this.logger.info("PostLoad-->数据加载,当前时间:{{}},e:{},", currentTime(new
	// Date()), JSONObject.toJSONString(e));
	// }

	public final String currentTime(Date time) {
		return DateFormatUtils.format(time, "yyyy-MM-dd HH:mm:ss:sss");
	}

}
